package com.lw.leetcode.str.b;

import java.util.Stack;

/**
 * create by idea
 * 71. 简化路径
 *
 * @author lmx
 * @version 1.0
 * @date 2021/11/21 17:34
 */
public class SimplifyPath {
    public String simplifyPath(String path) {
        path = path + '/';
        Stack<String> stack = new Stack<>();

        int length = path.length();
        int st = 1;
        int end;
        for (int i = 1; i < length; i++) {
            char c = path.charAt(i);
            if (c == '/') {
                end = i;
                if (end - st > 0) {
                    String item = path.substring(st, end);
                    if (!".".equals(item)) {
                        if ("..".equals(item)) {
                            if (!stack.empty()) {
                                stack.pop();
                            }
                        } else {
                            stack.push(item);
                        }
                    }
                }
                st = i + 1;
            }
        }

        return "/" + String.join("/", stack);
    }
}
